package com.yu.crm.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yu.crm.constants.WxConstant;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.*;

/**
 * @author pan
 * @since 2020/9/27 9:08
 */
public class AccessTokenTool {

    private static String APP_ID = WxConstant.WxConfigConstant.APP_ID;
    private static String APP_SECRET = WxConstant.WxConfigConstant.APP_SECRET;

    public static String getAccessToken() {
        String accessTokenUrl = WxConstant.WxRequestUrl.ACCESS_TOKEN_URL;
        accessTokenUrl = accessTokenUrl.replace("APPID", APP_ID).replace("APPSECRET", APP_SECRET);
        String accessToken = "";
        try {
            /**
             *  获取access_token
             *  成功返回的json : {"access_token":"ACCESS_TOKEN","expires_in":7200}
             *  失败放的json  : {"errcode":40013,"errmsg":"invalid appid"}
             */
            String result = HttpUtil.get(accessTokenUrl);
            Map<String,Object> token = JSONUtil.toBean(result, Map.class);
            accessToken = (String)token.get("access_token");
            if (token.get("errcode") == null) {
                //存入到常量中
                WxConstant.ACCESS_TOKEN =  accessToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }


    public static String CheckSignature(String str){
        String[] content=str.split("&");
        String signature=content[0].split("=")[1];
        String timestamp=content[2].split("=")[1];
        String nonce=content[3].split("=")[1];
        //第一步中填写的token一致
        String token= WxConstant.WxConfigConstant.TOKEN;

        ArrayList<String> list=new ArrayList<String>();
        list.add(nonce);
        list.add(timestamp);
        list.add(token);

        //字典序排序
        Collections.sort(list);
        //SHA1加密
        String checkSignature= SHA1Util.encode(list.get(0)+list.get(1)+list.get(2));
//        System.out.println(signature);
//        System.out.println(checkSignature);

        if(checkSignature.equals(signature)){
            return content[1].split("=")[1];
        }
        return null;
    }

    public static Map<String, String> getXmlData(InputStream inputStream) {
        Map<String, String> map = new HashMap<>(12);
        //截取xml
        SAXReader reader = new SAXReader();
        try {

            Document document = reader.read(inputStream);
            //获取根节点
            Element rootElement = document.getRootElement();
            // h获取所有的节点
            List<Element> elements = rootElement.elements();
            for (Element e : elements) {
                map.put(e.getName(), e.getStringValue());
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }
}
